package org.laobai.auth.service;

import org.laobai.auth.entity.UserInfo;
import org.laobai.auth.properties.JWTProperties;
import org.laobai.auth.utils.JwtUtils;
import org.laobai.common.asserts.Asserts;
import org.laobai.common.exception.BPException;
import org.laobai.common.struct.Pair;
import org.laobai.common.utils.CodecUtils;
import org.laobai.user.client.UserClient;
import org.laobai.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class AuthService {

    @Autowired
    private JWTProperties jwtProperties;

    @Autowired
    private UserClient userClient;


    public Pair<Boolean, String> login(String name, String pwd) {
        //根据name查询
        List<User> list = userClient.getUserByName(name);
        // 是否存在或者唯一
        Asserts.isNotNull(list,"用户名或密码有毛病");

        if(list.size()>1){
            throw new BPException(500,"数据重复，name为："+name);
        }
        // 加密pwd
        pwd = CodecUtils.md5Hex(pwd,"laobai");
        // 对比数据
        User userDB = list.get(0);
        if(userDB.getPwd().equals(pwd)){
            // 授权
            //userInfo
            // siyao
            //
            String token = JwtUtils.generateToken(new UserInfo(userDB.getId(), userDB.getName()),
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            return Pair.of(true,token);
        }
        return Pair.of(false,null);
    }
}
